<template>
  <div>
    <Card>
      <Tables ref="tables" searchable search-place="top" :loading="listLoading" :columns="columns" v-model="list">
        <template slot="handleButton">
          <Button v-if="userManager_btn_add" type="primary" @click="handleAdd"><Icon type="md-add" />新增</Button>
        </template>
        <template slot="searchButton">
          <div style="float:right">
            <Input placeholder="输入关键字搜索" class="search-input" v-model="listQuery.username">
            <Button @click="getList" slot="append" type="info" icon="ios-search"></Button>
            </Input>
          </div>
        </template>
        <template slot="action" slot-scope="props">
          <Button v-if="userManager_btn_edit" type="primary" @click="handleUpdate(props)" size="small">编辑</Button>
          <Divider type="vertical" />
          <Poptip confirm title="永久删除用户?" transfer @on-ok="handleDelete(props)">
            <Button v-if="userManager_btn_del" type="warning" size="small">删除</Button>
          </Poptip>
        </template>
      </Tables>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: left;">
          <Page v-show="!listLoading" :total="total" :page-size-opts="[50,100,500,1000,2000]" :current="listQuery.page" show-total show-sizer :page-size="listQuery.limit" @on-change="handleCurrentChange" @on-page-size-change="handleSizeChange"></Page>
        </div>
      </div>
    </Card>
    <Modal :title="textMap[dialogStatus]" v-model="dialogFormVisible" :mask-closable='false' :width="500">
      <Form ref="form" :model="form" :label-width="70" :rules="rules">
        <FormItem label="姓名" prop="name">
          <Input v-model="form.name"/>
        </FormItem>
        <FormItem label="账户" prop="username">
          <Input v-if="dialogStatus == 'create'" v-model="form.username"/>
          <Input v-else v-model="form.username" readonly/>
        </FormItem>
        <FormItem label="密码" prop="password" v-if="dialogStatus == 'create'">
          <Input type="password" v-model="form.password"/>
        </FormItem>
        <FormItem label="应用" prop="application">
          <Select v-model="form.application" style="width:250px" multiple>
            <Option v-for="item in  appList" :label="item.labelDefault" :value="item.value" :key="item.id"></Option>
          </Select>
        </FormItem>
        <FormItem label="性别">
          <Select v-model="form.sex" style="width:200px">
            <Option v-for="item in  sexOptions" :label="item.labelDefault" :value="item.value" :key="item.id"></Option>
          </Select>
        </FormItem>
        <FormItem label="描述">
          <Input type="textarea" :autosize="{minRows: 2,maxRows: 5}" v-model="form.description"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel('form')">取消</Button>
        <Button type="primary" v-if="dialogStatus=='create'" @click="create('form')">确 定</Button>
        <Button type="primary" v-else @click="update('form')">确 定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import Tables from '_c/tables'
import { mapGetters } from 'vuex'
import DepartSelector from './components/departSelector'
import {
  page,
  addObj,
  getObj,
  delObj,
  putObj
} from '@/api/admin/user/index'
import { getTypeValue } from '@/api/dict/dictValue/index'
export default {
  name: 'user',
  components: {
    Tables,
    'depart-selector': DepartSelector
  },
  data () {
    return {
      form: {
        username: undefined,
        name: undefined,
        sex: 'comm_sex_man',
        password: undefined,
        description: undefined,
        departName: undefined,
        departId: undefined,
        application: []
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      appList: [
        { labelDefault: '仓储系统', value: 'WMS', id: 'WMS' },
        { labelDefault: '物流系统', value: 'TMS', id: 'TMS' },
        { labelDefault: '计费系统', value: 'BMS', id: 'BMS' },
        { labelDefault: '订单系统', value: 'OMS', id: 'OMS' },
        { labelDefault: '账户系统', value: 'Account', id: 'Account' }
      ],
      rules: {
        name: [
          {
            required: true,
            message: '请输入用户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        username: [
          {
            required: true,
            message: '请输入账户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ],
        application: [
          {
            required: true,
            type: 'array',
            message: '请选择应用',
            trigger: 'change'
          }
        ]
      },
      dialogStatus: '',
      baseSearchColumns: [
        { title: '姓名', key: 'name' },
        { title: '账户', key: 'username' }
      ],
      columns: [
        { title: '姓名', key: 'name' },
        { title: '账户', key: 'username' },
        { title: '性别', key: 'sex' },
        { title: '身份',
          key: 'isSuperAdmin',
          render: (h, params) => {
            let content = '普通身份'
            let color = 'primary'
            if (params.row.isSuperAdmin === '1') {
              content = '超级管理员'
              color = 'red'
            }
            return h('Tag', { props: { color: color } }, content)
          }
        },
        { title: '备注', key: 'description' },
        { title: '最后时间', key: 'updTime' },
        { title: '更新人', key: 'updName' },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.tables.$scopedSlots.action(params)
            )
          }
        }
      ],
      list: [],
      listQuery: {
        page: 1,
        limit: 50,
        name: undefined,
        username: undefined
      },
      listLoading: false,
      total: 0,
      current: 1,
      sexOptions: [],
      dialogFormVisible: false,
      dialogDepartVisible: false,
      userManager_btn_edit: false,
      userManager_btn_del: false,
      userManager_btn_add: false
    }
  },
  created () {
    this.getList()
    this.userManager_btn_edit = this.elements['userManager:btn_edit']
    this.userManager_btn_del = this.elements['userManager:btn_del']
    this.userManager_btn_add = this.elements['userManager:btn_add']
    getTypeValue('comm_sex').then(response => {
      this.sexOptions = response.data.rows
    })
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    handlerAddDepart () {
      this.$refs.departSelector.onSubmit()
    },
    openDepartDialog () {
      this.dialogDepartVisible = true
    },
    closeDepartDialog (depart) {
      this.form.departName = depart.label
      this.form.departId = depart.id
      this.dialogDepartVisible = false
    },
    resetTemp () {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        password: undefined,
        description: undefined,
        departId: undefined,
        departName: undefined,
        application: []
      }
    },
    handleUpdate (props) {
      getObj(props.row.id)
        .then(response => {
          this.form = response.data
          // try {
          //   const depart = JSON.parse(response.data.departId)
          //   if (typeof depart === 'object' && depart) {
          //     this.form.departName = depart.name
          //     this.form.departId = depart.id
          //   } else {
          //     this.form.departId = response.data.departId
          //     this.form.departName = response.data.departId
          //   }
          // } catch (e) {
          //   console.log('error：部门转化json失败' + e)
          // }
          if (response.data.application) {
            this.form.application = response.data.application.split(',')
          } else {
            this.form.application = []
          }

          for (let i = 0; i < this.sexOptions.length; i++) {
            if (this.sexOptions[i].labelDefault === this.form.sex) {
              this.form.sex = this.sexOptions[i].value
            }
          }
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })
    },
    getList (params) {
      this.listLoading = true
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        })
    },
    create (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.form.application = this.form.application.join(',')
          addObj(this.form)
            .then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$Notice.success({
                title: '成功',
                desc: '添加成功'
              })
            })
        } else {
          return false
        }
      })
    },
    update (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          this.form.application = this.form.application.join(',')
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$Notice.success({
              title: '成功',
              desc: '修改成功'
            })
          })
        } else {
          return false
        }
      })
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    handleAdd () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleDelete (params) {
      delObj(params.row.id)
        .then(() => {
          this.$Notice.success({
            title: '成功',
            desc: '删除成功'
          })
          this.getList()
        })
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    }
  }
}
</script>
